package com.cat.common.util;


import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: ninglijun
 * @date: 15/12/25
 * @time: 下午3:16
 * @description:
 */
public class Signature {

    private static final String DEFULAT_ENCODING = "UTF-8";

    public static Map<String, String> mapSort(Map<String, String> map) {
        List<Map.Entry<String, String>> entries = new ArrayList(map.entrySet());

        Collections.sort(entries, new Comparator<Map.Entry<String, String>>() {
            public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                return o1.getKey().compareTo(o2.getKey());
            }
        });

        HashMap<String, String> result = new LinkedHashMap();
        for (Map.Entry<String, String> entry : entries) {
            result.put(entry.getKey(), entry.getValue());
        }
        return result;
    }

    public static String mapToSignString(Map<String, String> map, boolean encode) throws UnsupportedEncodingException {
        Map<String, String> sortedMap = mapSort(map);
        StringBuilder result = new StringBuilder();
        for (Map.Entry<String, String> entry : sortedMap.entrySet()) {
            if (result.length() > 0) {
                result.append("&");
            }
            result.append(entry.getKey()).append("=").append(encode ? URLEncoder.encode(entry.getValue(), DEFULAT_ENCODING) : entry.getValue());
        }
        return result.toString();
    }
}
